//
//  MyAESCryptBehavior.swift
//  RIBsTest
//
//  Created by lvzhao on 2024/5/25.
//

import Foundation
import CryptoSwift


class MyAESCryptBehavior: MyCryptBehavior {
    func encrypt(key: String?, strToEncode: String?) -> String? {
        guard let key = key else {return nil}
        guard let value = strToEncode else {
            return nil
        }
        //使用AES-128-ECB加密模式
        do {
            let aes = try AES(key: Padding.zeroPadding.add(to: key.bytes, blockSize: AES.blockSize), blockMode: ECB())
            
            //开始加密
            do {
                let encrypt = try aes.encrypt(value.bytes)
                return encrypt.toBase64()
            } catch {
                return nil
            }
        } catch {
            return nil
        }
        
    }
    
    func decrypt(key: String?, strToDecode: String?) -> String? {
        guard let key = key else {return nil}
        guard let value = strToDecode else {
            return nil
        }
        
        //使用AES-128-ECB解密模式
        do {
            let aes = try AES(key: Padding.zeroPadding.add(to: key.bytes, blockSize: AES.blockSize), blockMode: ECB())
            
            //开始解密
            do {
                let toDecode = Array(base64: value)
                let decrypted = try aes.decrypt(toDecode)
                return String(data: Data(decrypted), encoding: .utf8) ?? nil
            } catch {
                return nil
            }
        } catch {
            return nil
        }
    }
    
    
    
    
}
